package com.yl.auth.controller;


import com.alibaba.excel.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yl.auth.entity.Fangjian;
import com.yl.auth.model.entity.Chuangwei;
import com.yl.auth.model.entity.Laoren;
import com.yl.auth.model.entity.Tijian;
import com.yl.auth.model.entity.Yuangong;
import com.yl.auth.model.vo.LaoFangChuangVo;
import com.yl.auth.model.vo.LaorenQueryVo;
import com.yl.auth.model.vo.YuaGongPaiBanVo;
import com.yl.auth.service.*;
import com.yl.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author yl
 * @since 2023-06-15
 */
@RestController
@RequestMapping("/admin/auth/laoren")
@Api(tags = "市场销售-老人管理")
public class LaorenController {
    @Resource
    private LaorenService laorenService;

    @Resource
    private ChuangweiService chuangweiService;

    @Resource
    private YuangongService yuangongService;

    @Resource
    private FangjianService fangjianService;

    @Resource
    private TijianService tijianService;
    /**
     * 查看老人的全部信息
     * @return
     */
    @ApiOperation(value = "查询所有的老人信息")
    @GetMapping("/findAll")
    public Result findAll() {
        List<Laoren> list = laorenService.list();
        return Result.ok(list);
    }

    @ApiOperation(value = "查询老人状态为未预定的")
    @GetMapping("/find")
    public Result find() {
        List<Laoren> list = laorenService.find();
        return Result.ok(list);
    }
    @ApiOperation(value = "查询老人状态预定中的用来编辑预定登记")
    @GetMapping("/updateFind")
    public Result updateFind(){
        List<Laoren> list =  laorenService.updateFind();
        return Result.ok(list);
    }
    /**
     * 实现分页加条件查询
     * @param page
     * @param limit
     * @param laorenQueryVo
     * @return
     */
    @GetMapping("/findAllConnAndPage/{page}/{limit}")
    @ApiOperation(value = "老人分页查询 条件 ")
    public Result findAllConnAndPage(@PathVariable("page") @ApiParam("当前页") Long page,@PathVariable("limit") @ApiParam("总条数") Long limit,
                                    @ApiParam("老人类") LaorenQueryVo laorenQueryVo) {
        Page<Laoren> pageParm = new Page<Laoren>(page, limit);
        LambdaQueryWrapper<Laoren> wrapper = new LambdaQueryWrapper<>();
        String name = laorenQueryVo.getName();
        String idNumber = laorenQueryVo.getIdNumber();
        String bedId = laorenQueryVo.getBedId();
        String status = laorenQueryVo.getStatus();
        if (!StringUtils.isEmpty(name)) {
            wrapper.like(Laoren::getName, name);
        }
        if (!StringUtils.isEmpty(idNumber)) {
            wrapper.eq(Laoren::getIdNumber, idNumber);
        }
        if (!StringUtils.isEmpty(bedId)) {
            wrapper.eq(Laoren::getBedId, bedId);
        }
        if (!StringUtils.isEmpty(status)) {
            wrapper.eq(Laoren::getStatus, status);
        }
        wrapper.orderByDesc(Laoren::getId);
        IPage<Laoren> pageModel = laorenService.page(pageParm, wrapper);
        List<Laoren> records = pageModel.getRecords();
        for (Laoren record : records) {
            Long id = record.getId();
            LambdaQueryWrapper<Laoren> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.eq(Laoren::getId, id);
            List<Laoren> list = laorenService.list(queryWrapper);
            if (list != null) {
                for (Laoren laoren : list) {
                    Integer laorenStatus = laoren.getStatus();
                    if (laorenStatus == 2) {
                        Chuangwei chuangwei = chuangweiService.getById(record.getBedId());
                        Fangjian fangjian = fangjianService.getById(record.getRoomId());
                        record.setBedName(fangjian.getRoomNo()+"-"+chuangwei.getBedNo());
                    }
                }
            }
        }
        return Result.ok(pageModel);
    }

    /**
     * 老人用药计划分页模糊查询
     * @param page
     * @param limit
     * @param
     * @return
     */
    @GetMapping("/findAll/{page}/{limit}")
    @ApiOperation(value = "用药计划分页模糊查询")
    public Result findAll(@PathVariable @ApiParam("页码") Long page,
                          @PathVariable @ApiParam("记录") Long limit,
                          @ApiParam("老人姓名")String name){
        Page<LaoFangChuangVo> page1=new Page<>(page,limit);
        Page<LaoFangChuangVo> list=laorenService.findAll(page1,name);
        return Result.ok(list);
    }


        /**
         * 老人健康档案分页模糊查询
         */
        @ApiOperation(value = "老人健康档案分页模糊查询")
        @GetMapping("/getPage/{page}/{limit}")
        public Result getPage (@PathVariable @ApiParam("页码") Long page,
                @PathVariable @ApiParam("记录") Long limit,
                               @ApiParam("老人姓名")String name, String searchParam){
            Page<LaoFangChuangVo> page1 = new Page<>(page, limit);
            Page<LaoFangChuangVo> list = laorenService.getPage(page1, name, searchParam);
            return Result.ok(list);
        }
        @PostMapping("/saveLao")
        @ApiOperation(value = "添加老人基本信息")
        public Result saveLao (@RequestBody Laoren laoren){
            if(laoren.getId()!=null) {
                laorenService.updateById(laoren);
            }else {
                laorenService.save(laoren);
                //获取到新增后的老人id
                Long id = laoren.getId();
                //创建一个体检对象
                Tijian tijian = new Tijian();
                //给体检对象赋值一个老人id
                tijian.setLaorenId(id);
                //在数据中添加指定的老人的数据
                tijianService.save(tijian);
            }
            return Result.ok();
        }
        /*图片上传上传图片接口*/
        /*图片上传地址*/
        String fileSavePath = "D:/ylHomes/ylHomes/public/upload/";
        /*格式化时间*/
        private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd/");
        @PostMapping("/saveUpload")
        @ApiOperation(value = "图片上传")
        @CrossOrigin
        public Result uploadFile (@ApiParam(name = "file", value = "上传", required = true) @RequestPart("file") MultipartFile file, HttpServletRequest request){
            /*将时间转化成字符串*/
            Date date = new Date();
            String directory = simpleDateFormat.format(date);
            /*文件路径是否存在
             * 如果不存在,则创建
             */
            File dir = new File(fileSavePath + directory);
            if (!dir.exists()) {
                dir.mkdirs();
            }
            /*获取图片的名字*/
            String imageName = file.getOriginalFilename();
            System.out.println("图片上传位置" + fileSavePath + directory);
            /*给文件创建一个新的名字*/
            String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().lastIndexOf("."));
            /*图片新的名字*/
            String newFileName = UUID.randomUUID().toString().replaceAll("-", "") + suffix;
            System.out.println("上传的图片位置" + fileSavePath + directory + newFileName);
            /*创建新文件*/
            File newFile = new File(fileSavePath + directory + newFileName);
            try {
                file.transferTo(newFile);
                String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + "/images/" + directory + newFileName;
                System.out.println("图片上传成功的url:" + url);
                String sql = "/upload/" + directory + newFileName;
                /*返回给前端的字符串地址,然后添加的时候将这一串字符串加入到数据库中*/
                return Result.ok(sql);
            } catch (IOException e) {
                return Result.ok();
            }
        }

        /**
         * 获取到指定的id回显数据
         * @param id
         * @return
         */
        @GetMapping("/get/{id}")
        @ApiOperation(value = "获取到指定的id回显数据")
        public Result get(@PathVariable @ApiParam("老人id") Long id){
            Laoren laoren = laorenService.getById(id);
            if(laoren.getRoomId()!=null&&laoren.getBedId()!=null) {
                Fangjian fangjian = fangjianService.getById(laoren.getRoomId());
                Chuangwei chuangwei = chuangweiService.getById(laoren.getBedId());
                String roomNo = fangjian.getRoomNo().toString();
                String bedNo = chuangwei.getBedNo();
                laoren.setChuangWeiBed(roomNo+"-"+bedNo);
            }
            return Result.ok(laoren);
        }

        /**
         * 保存健康信息
         * @return
         */
        @PostMapping("/savejiankuang")
        @ApiOperation(value = "保存健康信息")
        public Result savejiankuang (@RequestBody Laoren laoren){
            laorenService.savejianKuang(laoren);
            return Result.ok();
        }
        @DeleteMapping("/removeById/{id}")
        @ApiOperation(value = "删除老人的信息")
        public Result removeById(@PathVariable Long id) {
            laorenService.removeById(id);
            return Result.ok();
        }

        @GetMapping("/findPaiBan")
        @ApiOperation(value = "排班设置新增护工列表+模糊查询")
        public Result findPaiBan(@ApiParam("排班封装类") YuaGongPaiBanVo yuaGongPaiBanVo){
            List<Yuangong> list = yuangongService.listPaiBan(yuaGongPaiBanVo);
            return Result.ok(list);
        }
        @GetMapping("/quedingPaiban/{id}/{hid}/{week}")
        @ApiOperation(value = "排班确定按钮功能")
        public Result quedingPaiban(@PathVariable @ApiParam("老人id") Long id,@PathVariable @ApiParam("员工id") Integer hid,
                                        @PathVariable @ApiParam("星期状态") Integer week) {
            Yuangong yuangong = yuangongService.getById(hid);
            yuangong.setWeek(week);
            yuangong.setLaorenId(id);
            yuangongService.updateById(yuangong);
            return Result.ok(yuangong);
        }

        @GetMapping("/getLaorenHugong/{id}")
        @ApiOperation(value = "查询已经给老人安排的护工")
        public Result getLaorenHugong(@PathVariable @ApiParam("老人id") Integer id) {
            LambdaQueryWrapper<Yuangong> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Yuangong::getLaorenId,id);
            List<Yuangong> list = yuangongService.list(wrapper);
            return Result.ok(list);
        }

    @GetMapping("/updatePaiBan/{id}/{hid}/{week}/{newHid}")
    @ApiOperation("修改当前排班护工")
    public Result updatePaiBan(@PathVariable Long id,@PathVariable Integer hid,@PathVariable Integer week
            ,@PathVariable Integer newHid){
        boolean b = yuangongService.lambdaUpdate().eq(Yuangong::getId, hid).set(Yuangong::getLaorenId, 0).set(Yuangong::getWeek, 0).update();
        if(b){
            boolean c = yuangongService.lambdaUpdate().eq(Yuangong::getId, newHid).set(Yuangong::getLaorenId, id).set(Yuangong::getWeek, week).update();
            if(c){
                return Result.ok("排班成功");
            }else {
                return Result.fail("排班失败");
            }
        }
        return Result.ok("排班成功");
    }

}

